package falcon.script;

import falcon.common.Errno;
import falcon.common.Log;

public final class FalconLangSysCall {

	public static int call(String name, String[] args, String[] rets) {
		int errno = Errno.SUCCESS;
		try {
			if ("format".equals(name)) {
				errno = format(args, rets);
			} else if ("len".equals(name)) {
				errno = len(args, rets);
			} else if ("sub".equals(name)) {
				
			} else if ("log".equals(name)) {
				errno = log(args, rets);
			} else if ("find".equals(name)) {
				
			} else if ("match".equals(name)) {
				
			}
		} catch (Exception e) {
			errno = Errno.COM_CATCH_EXCEPTION;
			Log.log(e, "");
		}
		return errno;
	}
	
	private static int format(String[] args, String[] rets) {
		if (args.length < 1) {
			return Errno._INVALID_ARGUMENT;
		}
		String f = args[0];
		Object[] a = new Object[args.length - 1];
		for (int i = 0; i < a.length; i ++) {
			a[i] = args[i + 1];
		}
		rets[1] = String.format(f, a);
		return Errno.SUCCESS;
	}
	
	private static int len(String[] args, String[] rets) {
		if (args.length != 1) {
			return Errno._INVALID_ARGUMENT;
		}
		String v = args[0];
		rets[1] = Integer.toString(v.length());
		return Errno.SUCCESS;
	}
	
	private static int log(String[] args, String[] rets) {
		if (args.length < 1) {
			return Errno._INVALID_ARGUMENT;
		}
		String f = args[0];
		Object[] a = new Object[args.length - 1];
		for (int i = 0; i < a.length; i ++) {
			a[i] = args[i + 1];
		}
		Log.log(f, a);
		return Errno.SUCCESS;
	}
}
